<?php
/**
 * @copyright   Copyright (c) 2017 http://www.brsttech.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 用户登录授权等页面
 */
namespace app\webapp\controller;
use EasyWeChat\Factory; 

class Account extends Base{


    public $backurl = 'www';
    public $app_id  = 'xxx';
    public $secret  = 'xxx';

    /**
    * 微信基础配置
    * @return void
    */
    protected function config(){
        $config = [
            'app_id' => $this->app_id,
            'secret' => $this->secret,
            'response_type' => 'array',
        ];
        return Factory::officialAccount($config);
    } 
    
    /**
     * 判断是否登录
     * @return void
     */
    public function index(){
        if($this->getLoginUser()){
            return $this->redirect(url('webapp/index/index'));
        }else{
            return $this->redirect(url('webapp/Account/putWechat'));
        }
    }

    /**
     *  发起微信授权
     */
    public function putWechat(){
        $response = self::config()->oauth->scopes(['snsapi_userinfo'])->redirect(url('webapp/account/getWechat',[],true,$this->backurl));
        return $response->send();
    }

    /**
     *  回调微信授权
     */
    public function getWechat(){
        $code = input('get.code/s');
        if(!$code){
            return $this->redirect(url('webapp/account/putWechat'));
        }
        $user = self::config()->oauth->user();
        $data['wechat_id'] = $user->getID();
        $data['nickname']  = $user->getName();
        $userinfo = model('user')->get(['wechat_id' => $data['wechat_id']]);
        if(empty($userinfo)){
            $insert_id = model('User')->reguser($data);
            $userinfo  = model('User')->get($insert_id); //获取当前用户信息
        }
        $this->setLoginSession($userinfo);
        return $this->redirect(url('webapp/index/index'));
    }

    /**
     *  微信接入授权验证
     */
    public function wechatAccount(){
        $response = self::config()->server->serve();
        $response->send();
    }

}